package sign;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import properties.AutoQDProperties;
import properties.User;
import util.EmailSender;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class InSign implements Job {
    private static final Logger logger = LoggerFactory.getLogger(InSign.class);
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final Random random = new Random();

    private AutoQDProperties properties;
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 20,
            1, TimeUnit.MINUTES, new ArrayBlockingQueue<>(20));

    public static void main(String[] args) {
        AutoQDProperties autoQDProperties = new AutoQDProperties();
        for (User user : autoQDProperties.getUsers()) {
            Signer signer = new Signer(user);
            try {
                signer.login();
                signer.inSign();
            } catch (Exception e) {
                logger.error("用户[{}]打卡异常", user.getName());
                EmailSender.send(false,"[" + sdf.format(new Date()) + "]上班打卡失败:\n" + e.getMessage(), user.getEmail());
            }
        }
    }


    public InSign() {
        properties = new AutoQDProperties();
    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        List<User> users = properties.getUsers();

        for (User user : users) {
            Future<Object> submit = threadPoolExecutor.submit(() -> {
                return sign(random.nextInt(15 * 60 * 1000 - 1000), user);
            });
        }


    }

    public Object sign(int millis, User user) {
        try {
            logger.info(sdf.format(new Date(System.currentTimeMillis() + millis)) + "-进行上班打卡");
            Thread.sleep(millis);
            Signer signer = new Signer(user);
            signer.login();
            signer.inSign();
        } catch (Exception e) {
            logger.error("用户[{}]打卡异常", user.getName());
            EmailSender.send(false,"[" + sdf.format(new Date()) + "]上班打卡失败:\n" + e.getMessage(), user.getEmail());
        }
        return null;
    }
}

